import 'dart:io';
import 'package:intl/intl.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:share_plus/share_plus.dart';
import '../models/transaction.dart';
import 'database_service.dart';

class ExportService {
  static final _dateFormat = DateFormat('yyyy-MM-dd HH:mm:ss');
  static final _numberFormat = NumberFormat('#,##0.00');

  /// 导出所有交易记录为CSV
  static Future<String> exportToCSV() async {
    final transactions = await DatabaseService.instance.getAllTransactions();
    final csvData = _generateCSV(transactions);
    final file = await _saveToFile(csvData);
    return file.path;
  }

  /// 生成CSV内容
  static String _generateCSV(List<Transaction> transactions) {
    final buffer = StringBuffer();
    
    // 添加CSV头
    buffer.writeln('日期,类型,分类,标题,金额,备注');
    
    // 添加交易记录
    for (final transaction in transactions) {
      final type = transaction.type == TransactionType.expense ? '支出' : '收入';
      final amount = _numberFormat.format(transaction.amount);
      final date = _dateFormat.format(transaction.date);
      final note = transaction.note?.replaceAll(',', '，') ?? ''; // 替换逗号以避免CSV格式问题
      
      buffer.writeln(
        '$date,$type,${transaction.category},${transaction.title},$amount,$note',
      );
    }
    
    return buffer.toString();
  }

  /// 保存到文件
  static Future<File> _saveToFile(String data) async {
    final now = DateTime.now();
    final fileName = 'bookkeeping_export_${now.year}${now.month}${now.day}.csv';
    
    if (Platform.isAndroid) {
      // 检查并请求权限
      final status = await Permission.storage.request();
      if (!status.isGranted) {
        throw '需要存储权限才能导出数据';
      }
    }
    
    final directory = await getApplicationDocumentsDirectory();
    final file = File('${directory.path}/$fileName');
    return file.writeAsString(data);
  }

  /// 分享CSV文件
  static Future<void> shareCSV(String filePath) async {
    final file = XFile(filePath);
    await Share.shareXFiles(
      [file],
      subject: '记账数据导出',
    );
  }
} 